package stats;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentLinkedQueue;


public class RunnableLinkedQueueStatsService implements IStatsService, Runnable
{
	private ConcurrentLinkedQueue<String>	queue	= new ConcurrentLinkedQueue<String>();
	Map<String, Number>						copy	= new HashMap<String, Number>();
	public transient boolean				active	= true;
	public Thread							t;

	public RunnableLinkedQueueStatsService ()
	{
		t = new Thread(this);
		t.start();
	}

	public void notify ( String key )
	{
		queue.add(key);
	}

	public Map<String, Number> getStats ( )
	{
		return copy;
	}

	public void run ( )
	{
		String key;
		while (active || queue.peek() != null)
		{
			while ( ( key = queue.poll() ) != null)
			{
				Number value = copy.get(key);
				if (value == null)
				{
					value = 0;
				}
				copy.put(key, value.longValue() + 1);
			}
		}
	}

	public void stop ( )
	{
		active = false;
		try
		{
			t.join();
		}
		catch (InterruptedException e)
		{
			e.printStackTrace();
		}
	}
}
